package com.kintreda.ieco_server.module.api.web;

import com.github.wxpay.sdk.WXPayConstants.SignType;
import com.kintreda.ieco_server.bean.order.PayOrder;
import com.kintreda.ieco_server.core.web.R;
import com.kintreda.ieco_server.module.account.service.IUserService;
import com.kintreda.ieco_server.module.api.service.IPayOrderService;
import com.kintreda.ieco_server.module.order.service.IStatisticsService;
import com.kintreda.ieco_server.module.organization.service.IOrganizationService;
import com.kintreda.ieco_server.util.Parameters;
import com.kintreda.ieco_server.util.wxpay.WXPay;
import com.kintreda.ieco_server.util.wxpay.WXPayConfig;
import com.kintreda.ieco_server.util.wxpay.WXPayConstants;
import com.kintreda.ieco_server.util.wxpay.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @Created by IntelliJ IDEA
 * @Project_Name ieco_server
 * @Package com.kintreda.ieco_server.module.api.wxpay
 * @Author ZhongYao_H
 * @Date 2019/5/18:17:17
 * @Year 2019 Month 05 Day 18
 * @Date_zh 2019 年 五月 星期六
 */
@Controller
@RequestMapping("/api/wxpay")
public class ApiWxPayController {

    WXPayConfig config = new WXPayConfig();

    @Autowired
    IUserService userService;
    @Autowired
    IPayOrderService payOrderService;
    @Autowired
    IStatisticsService statisticsService;
    @Autowired
    IOrganizationService organizationService;


    @RequestMapping(value = "/getopenid",method = RequestMethod.POST)
    @ResponseBody
    public Object getUserOpenId(String code) throws Exception {
        String get = WXPay.httpsRequest("https://api.weixin.qq.com/sns/jscode2session?appid="+Parameters.APPID+"&secret="+Parameters.SECRET+"&js_code="+code+"&grant_type=authorization_code", "GET", null);
        return get;
    }





    @RequestMapping(value = "/placeorder", method = RequestMethod.POST)
    @ResponseBody
    public Object placeOrder(String openid, HttpServletRequest request,String num) throws Exception {

        try {
            userService.findUserByOpenId(openid).getId();
            WXPay wxPay = new WXPay(new WXPayConfig());
            PayOrder payOrder = new PayOrder();
            payOrder.setTotal(Parameters.SACK_PRICE.intValue()*Integer.parseInt(num)+"");
            payOrder.setBody("购买环保袋");
            String ipaddress = WXPayUtil.getRemoteHost(request);
            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put("total_fee",String.valueOf(Parameters.SACK_PRICE.intValue()*Integer.parseInt(num)));//单位分
//            hashMap.put("total_fee", String.valueOf(new BigDecimal(1).intValue()));//测试
            hashMap.put("out_trade_no", payOrder.getOrderId());
            hashMap.put("spbill_create_ip", ipaddress);
            hashMap.put("body", "IECO环保袋");
            hashMap.put("notify_url", "www.baidu.com");
            hashMap.put("trade_type", "JSAPI");
            hashMap.put("openid", openid);
            wxPay.fillRequestData(hashMap);
            String mapxml = WXPayUtil.mapToXml(hashMap);
            Map resultxmlmap = WXPayUtil.xmlToMap(WXPay.httpsRequest("https://api.mch.weixin.qq.com/pay/unifiedorder", "POST", mapxml));
            System.out.println("resultxmlmap = " + resultxmlmap);
            if (resultxmlmap.get("result_code").equals("SUCCESS") && resultxmlmap.get("return_code").equals("SUCCESS")) {
                Map<String, String> result = chooseWXPayMap(resultxmlmap.get("prepay_id"));
                result.put("code", "0");
                return result;
            }
            resultxmlmap.put("code", "500");
            resultxmlmap.put("msg", "下单失败稍后重试");
            payOrderService.save(payOrder);
            return resultxmlmap;
        } catch (Exception e) {
            e.printStackTrace();
            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put("code", "500");
            hashMap.put("msg", "登录失效");
            return hashMap;
        }


    }

    /**
     * 作用：生成微信支付所需参数，微信支付二次签名<br>
     * 场景：根据微信统一下单接口返回的 prepay_id 生成微信支付所需的参数
     * 接口文档地址：https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_7&index=6
     *
     * @param prepay_id 预支付id
     * @return 支付方法调用所需参数map
     * @throws Exception e
     */
    public Map<String, String> chooseWXPayMap(Object prepay_id) throws Exception {

        // 支付方法调用所需参数map
        Map<String, String> chooseWXPayMap = new HashMap<>();
        chooseWXPayMap.put("appId", config.getAppID());
        chooseWXPayMap.put("timeStamp", String.valueOf(WXPayUtil.getCurrentTimestamp()));
        chooseWXPayMap.put("nonceStr", WXPayUtil.generateNonceStr());
        chooseWXPayMap.put("package", "prepay_id=" + prepay_id);
        chooseWXPayMap.put("signType", WXPayConstants.HMACSHA256);
        WXPayUtil.getLogger().info("wxPay.chooseWXPayMap:" + chooseWXPayMap.toString());
        // 生成支付签名
        String paySign = WXPayUtil.generateSignature(chooseWXPayMap, config.getKey(), SignType.HMACSHA256);
        chooseWXPayMap.put("paySign", paySign);
        WXPayUtil.getLogger().info("wxPay.paySign:" + paySign);
        return chooseWXPayMap;
    }


    /**
     * 提现
     */
    @RequestMapping(value = "/withdrawal",method = RequestMethod.POST)
    @ResponseBody
    public Object withdrawal(String openid , String money,String type,String account,String name,String walletType  ){
        try {
            return statisticsService.wallte(openid,money,type,account,name,walletType);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("系统计算异常!请联系管理员");
        }
    }

}
